<template>
  <div class="right-content">
    <div class="search">
      <el-button type="primary" @click="handleAdd" size="small" v-hasPermi="['editor:documentTemplateInfo:add']">新增</el-button>
      <div class="btns">
        <el-input
          clearable
          v-model="keyword"
          placeholder="请输入关键字"
          style="width: 300px"
          maxlength="100"
          size="small"
          @keyup.enter.native="handleQuery"
          @clear="resetQuery"
        />
        <el-button class="search-btn" type="primary" size="small" @click="handleQuery">搜索</el-button>
        <el-button type="primary" plain size="small" @click="resetQuery">重置</el-button>
      </div>
    </div>
    <div class="list-wrapper">
      <el-table v-loading="loading" :data="dataList" style="width: 100%">
        <el-table-column label="序号" type="index" width="50" :index="indexMethod"/>
        <el-table-column prop="name" label="模板名称" />
        <el-table-column prop="version" label="版本号" />
        <el-table-column prop="classifyName" label="适用类型" />
        <el-table-column prop="ruleName" label="规范类型" />
        <el-table-column prop="templateUseCount" label="引用次数" />
        <el-table-column prop="createByName" label="负责人" />
        <el-table-column prop="createDept" label="发布部门" />
        <el-table-column prop="updateTime" label="更新日期" />
        <el-table-column prop="status" label="状态" width="80">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isPublished"
              size="mini"
              v-hasPermi="['editor:documentTemplateInfo:change']"
              @change="switchStatus(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handlePreview(scope.row)"
              >预览</el-button
            >
            <el-button type="text" size="mini" @click="handleEditContent(scope.row)" v-if="isAdmin || scope.row.hasOpPermission" v-hasPermi="['editor:documentTemplateInfo:editContent']"
              >编辑正文</el-button
            >
            <el-dropdown size="mini" v-if="isAdmin || scope.row.hasOpPermission" @command="(c) => handleCommand(c, scope.row)">
              <span class="el-dropdown-link"
                v-hasPermi="[
                  'editor:documentTemplateInfo:editInfo',
                  'editor:documentTemplateInfo:history',
                  'editor:documentTemplateInfo:remove',
                  'editor:documentTemplateInfo:upgrade',
                ]"
              >
                更多<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="1" v-hasPermi="['editor:documentTemplateInfo:editInfo']">编辑信息</el-dropdown-item>
                <el-dropdown-item command="2" v-hasPermi="['editor:documentTemplateInfo:history']">历史版本</el-dropdown-item>
                <el-dropdown-item command="3" v-hasPermi="['editor:documentTemplateInfo:remove']">删除</el-dropdown-item>
                <el-dropdown-item command="4" v-if="scope.row.isPublished" v-hasPermi="['editor:documentTemplateInfo:upgrade']">升版</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="business-pager p20 fr"
        v-show="dataTotal > 0"
        :background="true"
        :current-page.sync="queryParams.pageNum"
        :page-size.sync="queryParams.pageSize"
        :layout="'total, sizes, prev, pager, next, jumper'"
        :page-sizes="[10, 30, 50, 100]"
        :pager-count="7"
        :total="dataTotal"
        @size-change="handleSizeChange"
        @current-change="handlepageNumChange"
      />
    </div>
    <TemplateEditModal
      :visible.sync="editModalShow"
      :editData="editData"
      @onClose="onCloseDialog"
      :selectedNode="selectedNode"
      @onSuccess="onSuccess"
      :currentUser="currentUser"
    />
    <TemplateVersionHistoryModal
      :visible.sync="templateVersionHistoryModalVisible"
      :currentRow="currentRow"
    />
  </div>
</template>
<script>
import qs from "qs";
import { Message, MessageBox } from 'element-ui'
import TemplateEditModal from './TemplateEditModal'
import TemplateVersionHistoryModal from './TemplateVersionHistoryModal'
import {
  upgradeTemplate,
  getTemplateList,
  getTemplateInfo,
  publishTemplate,
  deleteTemplateInfo,
  getCurrentUserInfo
} from '@/api/business'

export default {
  name: 'RightContent',
  components: { TemplateEditModal, TemplateVersionHistoryModal },
  props: {
    selectedNode: {
      type: Object,
      default: () => ({})
    },
    openEditor: {
      type: Function,
      default: () => {}
    }
  },
  watch: {
    selectedNode(val) {
      this.onSearch()
    }
  },
  data() {
    return {
      templateVersionHistoryModalVisible: false,
      currentRow: {},
      editModalShow: false,
      editData: {},
      keyword: '',
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      dataList: [],
      dataTotal: 0,
      loading: false,
      currentUser: {}
    }
  },
  computed: {
    isAdmin() {
      return this.$store.getters.permissions?.[0] === "*:*:*"
    }
  },
  mounted() {
    this.getUser()
    this.handleQuery()
  },
  methods: {
    indexMethod(index) {
      return (
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
      );
    },
    handleCommand(command, row) {
      switch (command) {
        case "1": // 编辑信息
          this.handleEdit(row);
          break;
        case "2": // 历史版本
          this.templateVersionHistoryModalVisible = true
          this.currentRow = row
          break;
        case "3": // 删除
          this.handleDelete(row);
          break;
        case "4": // 升版
          this.handleUpgrade(row);
          break;
      }
    },
    handleAdd() {
      if (!this.selectedNode.id) {
        return Message.error('请先选择分类节点')
      }
      this.editData = {}
      this.editModalShow = true
    },
    resetQuery() {
      this.keyword = ''
      this.handleQuery()
    },
    handleQuery() {
      this.queryParams.current = 1
      this.onSearch()
    },
    onSearch() {
      this.loading = true
      getTemplateList({
        keyword: this.keyword,
        classifyId: this.selectedNode?.id,
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize
      })
        .then((res) => {
          this.dataList = res.data.list.map(i => {
            return {
              ...i,
              isPublished: i.status === '1'
            }
          })
          this.dataTotal = res.data.count
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleEdit(_data) {
      getTemplateInfo(_data.id).then((res) => {
        this.editData = res.data
        this.editModalShow = true
      })
    },
    handleEditContent(row) {
      const query = qs.stringify({
        id: row.id,
        editContentType: 'template'
      })
      window.open(`/editor/view?` + query, '_blank')
    },
    handleDelete(item) {
      MessageBox.confirm(`确认删除模板"${item.name}"吗？删除后不可恢复`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'business-dialog',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            deleteTemplateInfo(item.id)
              .then((res) => {
                Message.success('删除成功')
                this.onSearch()
              })
              .finally(() => {
                instance.confirmButtonLoading = false
                done()
              })
          } else {
            done()
          }
        }
      })
        .then(() => {})
        .catch((err) => {
          console.log(err)
        })
    },
    handlePreview(row) {
      const query = qs.stringify({
        id: row.id,
        editContentType: 'template',
        entry: 'preview'
      })
      window.open(`/editor/view?` + query, '_blank')
    },
    async handleUpgrade(row) {
      try {
        await MessageBox.confirm(`此操作将升版该模板，是否继续？`, '提示', {
          type: 'warning'
        })
        await upgradeTemplate({ sourceId: row.id })
        Message.success('升版成功')
        this.onSearch()
      } catch (error) {
        console.debug(error)
      }
    },
    onCloseDialog() {
      this.editData = {}
    },
    onSuccess() {
      this.editData = {}
      this.handleQuery()
    },
    publishFlag(item) {
      return item.status === '1'
    },
    async switchStatus(item) {
      try {
        await publishTemplate({
          id: item.id,
          status: item.status === '1' ? 0 : 1
        })
        Message.success(item.status === '1' ? '禁用成功' : '发布成功')
      } catch (error) {
        console.debug(error)
      } finally {
        this.onSearch()
      }
    },
    handleSizeChange(val) {
      if (this.queryParams.pageSize * val > this.dataTotal) {
        this.queryParams.pageNum = 1
      }
      this.onSearch()
    },
    handlepageNumChange() {
      this.onSearch()
    },
    getUser() {
      getCurrentUserInfo().then((res) => {
        this.currentUser = res.data
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "~@/assets/styles/editor.scss";
.editor-business-page .right-content .list-wrapper {
  height: calc(100vh - 168px);
}
</style>
